use std::{env, fs, io::{prelude::*, BufReader}, net::{TcpListener, TcpStream}};
//服务端获取请求与响应
fn handle_srv(mut stream: TcpStream) {
    let buf_reader = BufReader::new(&stream);
    // let request_line = buf_reader.lines().next().unwrap().unwrap(); //迭代下一行数据
    let request: Vec<_> = buf_reader
        .lines()
        .map(|result| result.unwrap())
        .take_while(|line| !line.is_empty())
        .collect();
    println!("服务端请求内容:{}", request.split_first().unwrap().0);
    //服务端输出响应
    // let response = "HTTP/1.1 200 OK\r\n\r\n";
    // println!("服务端响应内容:{:#?}", response);
    //服务端响应文本输出至前端页面
    // let (status_line, contents) = if request[0].starts_with("GET"){
    //     ("HTTP/1.1 200 OK\r\n\r\n", "Hi from Rust")
    // } else {
    //     ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "I don't know what you're asking for")
    // };
    // let response = format!("{status_line}\r\n\r\n{contents}\r\n\r\n");

    //以不同于其它请求的方式处理 / 请求
    let (status_line, filename) = if request[0] == "GET / HTTP/1.1" {
        // let (status_line, filename) = if request[0].starts_with("GET") {
        ("HTTP/1.1 200 OK\r\n\r\n", "index.html")
    } else {
        ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
    };
    let contents = fs::read_to_string(filename).unwrap();
    let response = format!("{}{}", status_line, contents);
    stream.write_all(response.as_bytes()).unwrap();
    stream.flush().unwrap();
}
//获取自定义端口号
fn get_port() -> u16 {
    let args: Vec<String> = env::args().collect();
    if args.len() > 1 {
        args[1].parse().expect("不是有效的端口号")
    } else {
        8080
    }
}
fn main() {
    // let cpu_core_num = thread::available_parallelism().unwrap().get();
    // println!("{} cpu cores", cpu_core_num);
    //获取自定义端口
    let port: u16 = get_port();
    // Tcp服务绑定
    // let listener = TcpListener::bind(("0.0.0.0", port)).unwrap();
    let listener = TcpListener::bind(format!("0.0.0.0:{}", port)).unwrap();
    // 获取到传入的Tcp流
    for stream in listener.incoming() {
        let stream = stream.unwrap();
        handle_srv(stream);
        // println!("Connection from {} established", stream.peer_addr().unwrap());
    }
}

